
package com.winning.sx.microframework.controller.busi;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.winning.dapi.data.entity.DataTable;
import com.winning.sx.microframework.common.util.Constains;
import com.winning.sx.microframework.common.util.FlowCodeUtil;
import com.winning.sx.microframework.common.util.SqlTool;
import com.winning.sx.microframework.controller.base.QRcodeController;
import com.winning.sx.microframework.model.exception.CustomException;
import com.winning.sx.microframework.model.manage.LoginSession;
import com.winning.sx.microframework.model.message.AjaxDataResponseMessage;
import com.winning.sx.microframework.model.message.AjaxTableResponseMessage;
import com.winning.sx.microframework.service.EasyService;
import com.winning.sx.microframework.service.sysmanage.ConstService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/busi/warehouseChange")
public class WarehouseChangeController {
    @Autowired
    EasyService easyService;

    @Autowired
    ConstService service;

    @RequestMapping(value = {"/", ""})
    public ModelAndView init() throws IOException, CustomException, SQLException {
        ModelAndView mv = new ModelAndView("/busi/warehouseChange");
        List type = service.queryCount("333");
        mv.addObject("type", type);
        LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
        Map<String, String> param = new HashMap();
        param.put("organizationType", "400001");
        param.put("superOrganizationId", login.getSuperOrgId());//全部客户的都展示，并不是展示中心自己的下属机构
        mv.addObject("organizationName", JSON.toJSON(service.queryMyOrg(param)).toString());

        Map eqRootClassP = new HashMap();
        eqRootClassP.put("superId", "0");
        eqRootClassP.put("validFlag", "100001");
        DataTable eqRootClassS = easyService.queryList("BASE_EqClass", eqRootClassP);
        List eqRootClass = eqRootClassS.getDataRows();
        mv.addObject("eqRootClass", eqRootClass);
        List brand = service.queryCount("300");
        mv.addObject("brand", brand);
        Map map = new HashMap();
        List eqClass = easyService.querySql("SELECT " +
                "  c1.name + '-' + c2.name name, " +
                "  c2.code " +
                "FROM BASE_EqClass c1 " +
                "  RIGHT JOIN BASE_EqClass c2 ON c1.id = c2.superId " +
                "WHERE c2.validFlag = '100001' AND c1.id IS NOT NULL ", map).getDataRows();
        mv.addObject("eqClass", eqClass);
        return mv;
    }

    @ResponseBody
    @RequestMapping(value = {"/queryChangeList"})
    public AjaxTableResponseMessage queryChangeList(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            DataTable all = easyService.querySql("select " +
                    "d.*,toW.organizationId oneOrganization2,toW.name toWName,toW.position toWPosition,ec.code oneCode,c1.code brandCode,e.id model,e.name,ec.name eqClassName,c1.name brandName,c2.name typeName,c3.name stateName,stC.name createStaffName,stU.name updateStaffName " +
                    "from BUSI_WarehouseChange d " +
                    "left join BASE_EquipmentDetail e on d.modelId=e.id " +
                    "left join BASE_Const c1 on e.brand=c1.code " +
                    "left join BASE_Const c2 on d.type=c2.code " +
                    "left join BASE_Const c3 on d.state=c3.code " +
                    "left join BASE_EqClass ec on e.type=ec.code " +
                    "left join BASE_Staff stC on stC.id=d.createStaffId " +
                    "left join BASE_Staff stU on stU.id=d.updateStaffId " +
                    "left join BASE_Warehouse toW on toW.id=d.toWarehouseId " +
                    "where d.validFlag='100001' " +
                    (param.get("warehouseId") == null ? "" : (" and d.warehouseId in (" + param.get("warehouseId") + ")")) +
                    (param.get("modelId") == null ? "" : (" and d.modelId =" + param.get("modelId"))) +
                    (param.get("getId") == null ? "" : (" and d.getId =" + param.get("getId"))) +
                    (param.get("searchKey") == null ? "" : (" and d.flowCode  like '" + param.get("searchKey")+"%'")) +
                    (param.get("modelType") == null ? "" : (" and e.type ='" + param.get("modelType") + "'")) +
                    (param.get("type") == null ? "" : (" and d.type in (" + param.get("type") + ")")) +
                    (param.get("state") == null ? "" : (" and d.state in (" + param.get("state")+")")) +
                    (param.get("b_createTime") != null ? (" and d.createTime>='" + param.get("b_createTime") + " 00:00:00'") : "") +
                    (param.get("e_createTime") != null ? (" and d.createTime<='" + param.get("e_createTime") + " 23:59:59'") : ""), param);
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/save"})
    public AjaxDataResponseMessage insert(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                Map param = new HashMap();
                param.put("id", map.get("id").toString());
                param.put("modelId", map.get("model").toString());
                param.put("warehouseId", map.get("warehouseId").toString());
                if(map.get("type").equals(Constains.WAREHOUSE_CHANGE_TYPE_22)){
                    if(!map.get("toWarehouseId").equals("")){
                        param.put("toWarehouseId", map.get("toWarehouseId").toString());
                    }
                }
                param.put("count", map.get("count").toString());
                param.put("type", map.get("type").toString());
                param.put("reason", map.get("reason").toString());
                param.put("flowCode", map.get("flowCode").toString().equals("") ? FlowCodeUtil.getFlowCode() : map.get("flowCode").toString());
                param.put("state", Constains.WAREHOUSE_CHANGE_STATE_1);
                if (param.get("id").toString().equals(""))
                    param.put("createStaffId", login.getStaffId().toString());
                else
                    param.put("updateStaffId", login.getStaffId().toString());
                easyService.save("BUSI_WarehouseChange", "id", param);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }
    @ResponseBody
    @RequestMapping(value = {"/update"})
    @Transactional(propagation= Propagation.REQUIRED)
    public AjaxDataResponseMessage update(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                Map param = new HashMap();
                param.put("id", map.get("id").toString());

                //过滤重复生效
                Map change= easyService.queryEntity("BUSI_WarehouseChange",  param);

                if(change==null||change.get("state").toString().equals("334002")){
                    throw new Exception("已经生效，请勿重复处理！");
                }

                //如果有getid则生成对应的使用记录 和二维码



                if(change.get("getId")!=null&&!"".equals(change.get("getId").toString())){
                    Map getParam=new HashMap();
                    getParam.put("id",change.get("getId").toString());
                    Map getInfo=easyService.queryEntity("BUSI_EquipmentGet",getParam);
                    getParam.put("id",change.get("getDetailId").toString());
                    Map getDetailInfo=easyService.queryEntity("BUSI_EquipmentGetDetail",getParam);
                    getParam.put("id",getDetailInfo.get("modelId").toString());
                    Map model=(Map)easyService.querySql("select " +
                            "d.*,eq.name typeName,c.name brandName " +
                            "from BASE_EquipmentDetail d left join BASE_EqClass eq on d.type=eq.code " +
                            "left join BASE_Const c on d.brand=c.code where d.id=:id",getParam).getDataRows().get(0);

                    for(int i=0;i<Integer.parseInt(change.get("count").toString());i++) {
                        Map equipment = new HashMap();
                        equipment.put("name", model.get("typeName") + "-" + model.get("brandName") + "-" + model.get("name") + "-" + model.get("code"));
                        equipment.put("oneCode", model.get("type"));
                        equipment.put("brandCode", model.get("brand"));
                        equipment.put("model", model.get("name") + "-" + model.get("code"));
                        equipment.put("oneCode", model.get("type"));
                        equipment.put("organizationId", getInfo.get("useOrgId").toString());
                        equipment.put("usePosition", getInfo.get("usePosition"));
                        equipment.put("buyTime", SqlTool.getNowTimeString());
                        equipment.put("changeId", change.get("id").toString());
                        equipment.put("inputStaffId", login.getStaffId().toString());
                        equipment.put("secrecy", "116001");
                        equipment.put("state", "203001");
                        Map qrCode = new HashMap();
                        qrCode.put("state", "500001");
                        qrCode.put("code", QRcodeController.createValCode(12));
                        easyService.save("BASE_QRcode", "id", qrCode);
                        equipment.put("QRCode", qrCode.get("id").toString());
                        easyService.save("BASE_Equipment", "id", equipment);
                    }

                }

                param.put("state", Constains.WAREHOUSE_CHANGE_STATE_2);
                param.put("updateStaffId", login.getStaffId().toString());
                Map detailParam=new HashMap();
                detailParam.put("equipmentId",map.get("model").toString());
                detailParam.put("warehouseId",map.get("warehouseId").toString());
                List detail=easyService.queryList("BASE_WarehouseDetail",detailParam).getDataRows();
                Map detailentity=new HashMap();
                if(map.get("type").toString().startsWith("3330")){
                    //入库
                    if(detail.size()>0){
                        Map entity=(Map)detail.get(0);
                        param.put("beforeCount",entity.get("count").toString());
                        detailentity.put("id",entity.get("id").toString());
                        detailentity.put("count",(Integer.parseInt(entity.get("count").toString())+Integer.parseInt(map.get("count").toString()))+"");
                    }else{
                        param.put("beforeCount","0");
                        detailentity.put("count",map.get("count").toString());
                        detailentity.put("equipmentId",map.get("model").toString());
                        detailentity.put("warehouseId",map.get("warehouseId").toString());
                    }
                }else{
                    //出库
                    if(detail.size()>0){
                        Map entity=(Map)detail.get(0);
                        param.put("beforeCount",entity.get("count").toString());
                        detailentity.put("id",entity.get("id").toString());
                        detailentity.put("count",(Integer.parseInt(entity.get("count").toString())-Integer.parseInt(map.get("count").toString()))+"");
                    }else{
                        param.put("beforeCount","0");
                        detailentity.put("count","-"+map.get("count").toString());
                        detailentity.put("equipmentId",map.get("model").toString());
                        detailentity.put("warehouseId",map.get("warehouseId").toString());
                    }
                    if(map.get("type").toString().equals(Constains.WAREHOUSE_CHANGE_TYPE_22)){
                        Map newChange = new HashMap();
                        newChange.put("modelId", map.get("model").toString());
                        newChange.put("warehouseId", map.get("toWarehouseId").toString());
                        newChange.put("count", map.get("count").toString());
                        newChange.put("type", Constains.WAREHOUSE_CHANGE_TYPE_12);
                        newChange.put("reason", map.get("reason").toString());
                        newChange.put("flowCode", map.get("flowCode").toString());
                        newChange.put("state", Constains.WAREHOUSE_CHANGE_STATE_1);
                        newChange.put("createStaffId", login.getStaffId().toString());
                        easyService.save("BUSI_WarehouseChange", "id", newChange);
                    }
                }
                easyService.save("BUSI_WarehouseChange", "id", param);
                easyService.save("BASE_WarehouseDetail","id",detailentity);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("修改失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }
    @ResponseBody
    @RequestMapping(value = {"/delete"})
    public AjaxDataResponseMessage delete(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                easyService.delete("BUSI_WarehouseChange", "id", map);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("删除失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }

}

